define(function(require, exports, module) {
	require('jquery');
	require('json2');
	var wsServer = 'ws://localhost:8080/xhtml-editor/websocket';
	var websocket = new WebSocket(wsServer);
	var listener=[];
	var messages=[];
	websocket.onopen = function(evt) {
		onOpen(evt);
	};
	websocket.onclose = function(evt) {
		onClose(evt);
	};
	websocket.onmessage = function(evt) {
		onMessage(evt);
	};
	websocket.onerror = function(evt) {
		onError(evt);
	};
	function onOpen(evt) {
		console.log("Connected to WebSocket server.");
		$.each(messages,function(i,v){
			websocket.send(v);
		});
		messages = [];
	}
	function onClose(evt) {
		console.log("Disconnected");
	}
	function onMessage(evt) {
		var data=$.parseJSON(evt.data);
		var listeners=listener[data.event];
		if(listeners){
			$.each(listeners,function(i,v){
				v(data.data);
			});
		}
	}
	function onError(evt) {
		console.log('Error occured: ' + evt.data);
	}
	function addListener(key,backhandler){
		if(key!=null&&backhandler!=null){
			var back=listener[key];
			if(back==null){
				back=[];
			}
			back.push(backhandler);
			listener[key]=back;
		}
	}
	module.exports ={
			send:send,
			addListener:addListener
	};
	function send(bean,method,data){
		var msg="{bean:'"+bean+"','method':'"+method+"',data:'"+JSON.stringify(data)+"'}";
		try{
			websocket.send(msg);
		}catch(e){
			messages.push(msg);
		}
	}
});
